package com.manage.common.config;

import com.manage.common.filter.JWTAuthenticationFilter;
import com.manage.common.filter.JWTAuthorizationFilter;
import com.manage.common.utils.AESUtil;
import com.manage.common.utils.JwtUtil;
import com.manage.dao.CmSysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private AESUtil aesUtil;

    private final UserDetailsService userDetailsService;
    private final AuthenticationConfiguration authenticationConfiguration;
    private final CmSysUserMapper cmSysUserMapper;
    public SecurityConfig(UserDetailsService userDetailsService,
                          AuthenticationConfiguration authenticationConfiguration,CmSysUserMapper cmSysUserMapper) {
        this.userDetailsService = userDetailsService;
        this.authenticationConfiguration = authenticationConfiguration;
        this.cmSysUserMapper = cmSysUserMapper;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 明确指定 bean 名称，确保可以被自动注入
    @Bean(name = "authenticationManager")
    public AuthenticationManager authenticationManager() throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http,
                                                   AuthenticationManager authenticationManager) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .authorizeHttpRequests(auth -> auth
                        // 放行 Swagger/Knife4j 相关路径
                        .requestMatchers(
                                "/doc.html",          // Knife4j 页面
                                "/webjars/**",        // Swagger 静态资源
                                "/v3/api-docs/**",    // Swagger API 文档
                                "/swagger-resources/**", // Swagger 配置
                                "/swagger-ui/**",  // 添加 Swagger UI 静态资源
                                "/favicon.ico"  ,      // 图标
                                "/caseManagement/**"
                        ).permitAll()
                        .requestMatchers("/auth/login","/auth/register").permitAll() // 放行登录接口
                        .anyRequest().authenticated()
                )
                .addFilter(new JWTAuthenticationFilter(authenticationManager(), aesUtil, cmSysUserMapper)
                )
                .addFilterBefore(new JWTAuthorizationFilter(authenticationManager,new JwtUtil()),
                        UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    /**
     * 全局 CORS 配置
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许的源（生产环境应替换为具体域名）
        configuration.addAllowedOriginPattern("*"); // 或指定域名，如 "http://localhost:8080"
        // 允许的请求方法
        configuration.addAllowedMethod("*"); // 推荐明确指定：GET, POST, PUT, DELETE 等
        // 允许的请求头
        configuration.addAllowedHeader("*");
        // 是否允许携带 Cookie
        configuration.setAllowCredentials(true);
        // 预检请求缓存时间（秒）
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有路径应用 CORS 配置
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
